
"use strict";
const Service = require("egg").Service;
const axios = require("axios");

const { Op } = require("sequelize");

const { failRes, successRes } = require("../extend/helper");
const { Journal } = require("../exception/Journal");
const await = require("await-stream-ready/lib/await");
const sUploadAvatar = require("./s_uploadAvatar");

function toInt(str) {
    if (typeof str === "number") return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
}

class sUser extends Service {
    // wa
    // 查询用户账户信息
    async wa_s_query(params) {
        let response = null;
        const { ctx } = this;
        try {
            const currentPage = toInt(params?.currentPage ?? 1);
            const pageSize = toInt(params?.pageSize ?? 10);
            const username = params?.userName ?? "";
            const status = (params?.status ?? "") || "";
            let whereMap = {
                username: {
                    [Op.like]: `%${username}%`,
                },
                status,
                id: {
                    [Op.like]: `%${params?.id ?? ""}%`, // 使用 Op.like 实现模糊匹配
                }
            };
            if (status === "") {
                whereMap = {
                    username: {
                        [Op.like]: `%${username}%`,
                    },
                };
            }
            const result = await ctx.model.Users.findAndCountAll({
                where: whereMap,
                order: [["id", "ASC"]], // 排序
                attributes: [
                    "id",
                    "nickName",
                    "avatar",
                    "userName",
                    "userPassword",
                    "status",
                    "remarks",
                    "totals",
                    "createdAt",
                    "updatedAt",
                ],
                limit: pageSize, // 每页多少条
                offset: pageSize * (currentPage - 1), // 跳过多少条
            });
            console.log(result?.count ?? 0, "<=== (result?.count ?? 0)");
            await Journal(ctx, { operatorType: "账号管理 -> 查询", code: 200 });
            response = successRes({
                records: result?.rows ?? [],
                total: result?.count ?? 0,
                pageSize,
                currentPage,
            });
        } catch (error) {
            console.error(error, "<---- error - 账号管理查询");
            await Journal(ctx, { operatorType: "账号管理 -> 查询", code: 401 });
            response = failRes(401);
        }
        return response;
    }
    //查询用户余额

    async wa_s_getUserBalance(params) {
        let response = null;
        const { ctx } = this;
        try {
            const result = await ctx.model.Users.findOne({
                where: {
                    id: params.id,
                },
                attributes: ["totals"], // 返回字段
            });
            await Journal(ctx, { operatorType: "账号管理 -> 查询", code: 200 });
            response = successRes({
                records: result || 0,
            });
        }catch (error) {
            console.error(error, "<---- error - 查询用户余额");
            await Journal(ctx, { operatorType: "查询用户余额", code: 401 });
            response = failRes(401);
        }
        return response;

    }

    // 用户注册新增
    async wa_s_create(params) {
        let response = null;
        const { ctx } = this;
        let transaction;
        try {
            // 建立事务对象
            transaction = await ctx.model.transaction();
            const result_data = await ctx.model.Users.findOne({
                where: {
                    userName: params?.userName ?? "",
                },
            });
            if (result_data) {
                response = failRes(107);
                await Journal(ctx, {
                    operatorType: "微信小程序 -> 用户注册",
                    code: 107,
                });
            } else {
                await ctx.model.Users.create(params, { transaction });
                response = successRes({
                    member: params?.userName ?? "",
                    token: "",
                    tokenExpired: "",
                });
                await Journal(ctx, {
                    operatorType: "微信小程序 -> 用户注册",
                    code: 200,
                });
            }
            await transaction.commit();
        } catch (error) {
            console.error(error, "<---- error - 用户注册");
            await transaction.rollback();
            await Journal(ctx, { operatorType: "微信小程序 -> 用户注册", code: 401 });
            response = failRes(401);
        }
        return response;
    }

    // 小程序端用户登录
    async wa_s_login(params) {
        // console.log(params, '<---- params - 用户登录');
        let response = null;
        const { ctx, app } = this;
        try {
            // 建立事务对象
            const result_data = await ctx.model.Users.findOne({
                where: {
                    userName: params?.userName ?? "",
                },
            });

            if (result_data) {
                // 判断账号是否存在 -- 存在
                if (
                    result_data?.userPassword === params?.userPassword &&
                    result_data.status === 1
                ) {
                    // 用户输入的密码与数据库的密码是否匹配 -- 密码正确登陆成功
                    const expiresIn = 60 * 60 * 24; // 有效期24小时
                    // 生成Token
                    const token = await app.jwt.sign(
                        {
                            id: result_data?.id ?? "",
                            username: result_data?.userName ?? "", // 需要存储的Token数据
                        },
                        app.config.jwt.secret,
                        {
                            expiresIn: expiresIn, // 有效期时间
                        }
                    );
                    //更新token
                    await result_data.update({ token: token });

                    response = successRes(
                        Object.assign({}, result_data.dataValues, {
                            tokenExpired: new Date().getTime() + 60 * 60 * 24 * 1000,
                        })
                    );
                    // console.log("result_data.nickName====>", result_data.nickName);

                    await Journal(ctx, {
                        operatorType: "微信小程序 -> 用户登录",
                        code: 200,
                    });
                } else if (result_data && result_data.status !== 1) {
                    await Journal(ctx, { operatorType: "微信小程序 -> 登录", code: 105 });
                    response = failRes(105);
                } else {
                    // 密码错误
                    response = failRes(104);
                    await Journal(ctx, {
                        operatorType: "微信小程序 -> 用户登录",
                        code: 104,
                    });
                }
            } else {
                // 账号不存在
                response = failRes(103);
                await Journal(ctx, {
                    operatorType: "微信小程序 -> 用户登录",
                    code: 103,
                });
            }
        } catch (error) {
            console.error(error, "<---- error - 用户登录");
            await Journal(ctx, { operatorType: "微信小程序 -> 用户登录", code: 401 });
            response = failRes(401);
        }
        return response;
    }
    // 用户信息修改
    async wa_s_update(params) {
        console.log(params, "<= params");
        let response = null;
        try {
            const { ctx } = this;
            await ctx.model.Users.update(
                params,
                {
                    where: { id: params.id },
                    attributes: { extends: ["id"] },
                }
                // console.log(params, '<---- params - 账号管理编辑数据')
            );

            await Journal(ctx, { operatorType: "账号管理 -> 编辑", code: 200 });
            response = successRes();
        } catch (error) {
            console.error(error, "<---- error - 账号管理编辑");
            await Journal(ctx, { operatorType: "账号管理 -> 编辑", code: 401 });
            response = failRes(401);
        }
        return response;
    }

    // 用户账户删除
    async wa_s_delete(params) {
        console.log(params, "<======= params");
        let response = null;
        const { ctx } = this;
        try {
            await ctx.model.Users.destroy({
                where: { id: params.id },
            });
            await Journal(ctx, { operatorType: "账号管理 -> 删除", code: 200 });
            response = successRes();
        } catch (error) {
            console.error(error, "<---- error - 账号管理删除");
            await Journal(ctx, { operatorType: "账号管理 -> 删除", code: 401 });
            response = failRes(401);
        }
        return response;
    }

    //Web端用户购物车查询
    async pc_s_query_cart(params) {
        console.log("paramsUser:===============> ", params);
        let response = null;
        const { ctx } = this;
        try {
            const currentPage = toInt(params?.currentPage ?? 1);
            const pageSize = toInt(params?.pageSize ?? 10);
            const result = await ctx.model.Shoppingcarts.findAndCountAll({
                where: {
                    uid: params?.uid ?? "",
                },
                include: [
                    //关联查询商品表
                    {
                        model: ctx.model.Products,
                        where: {
                            title: { [Op.like]: `%${params?.title ?? ""}%` },
                        },
                        attributes: ["id","title", "decs", "price", "defaultImg"],
                        through: { attributes: ["pcount", "sprice"] },
                    },
                ],
                model: ctx.model.Shoppingcarts,
                attributes: ["id", "uid"],

                order: [["id", "ASC"]], // 排序

                limit: pageSize, // 每页多少条
                offset: pageSize * (currentPage - 1), // 跳过多少条
            });
            //查询数据处理
            const _data = JSON.parse(JSON.stringify(result?.rows ?? []));
            _data?.forEach(_item => {
                if (_item?.products?.length > 0) {
                    _item?.products?.forEach(_product => {
                        console.log("_product: ", _product);
                        _product.pcount = _product?.shoppingcarts_products?.pcount ?? 0;
                        try {
                            delete _product.shoppingcarts_products;
                        } catch (error) { }
                    });
                }
            });
            await Journal(ctx, { operatorType: "购物车商品信息 -> 查询", code: 200 });
            response = successRes({
                records: _data,
                total: result?.count || 0,
                pageSize,
                currentPage,
            });
        } catch (error) {
            console.error(error, "<---- error - 购物车商品信息查询");
            await Journal(ctx, { operatorType: "购物车商品信息 -> 查询", code: 401 });
            response = failRes(401);
        }
        return response;
    }
    // Web端购物车商品信息 -> 更新
    async pc_s_update_cart(params) {
        let response = null;
        let transaction;
        const { ctx } = this;
        try {
            // 建立事务对象
            transaction = await ctx.model.transaction();
            params;
            await ctx.model.ShoppingcartsProducts.update(
                params,
                {
                    where: {
                        sid: params?.sid?? "",
                        pid: params?.pid?? "",
                    },
                    attributes: { extends: ['id', "sid", "pid"] }
                },
                { transaction }
            );
            await transaction.commit();
            await Journal(ctx, { operatorType: '购物车商品更新 -> 编辑', code: 200 });
            response = successRes();
        } catch (error) {
            console.error(error, '<---- error - 购物车商品更新编辑');
            await transaction.rollback();
            await Journal(ctx, { operatorType: '购物车商品更新 -> 编辑', code: 401 });
            response = failRes(401);
        }
        return response;
    }


    //用户地址查询
    async wa_s_query_address(params) {
        // console.log('paramsProducts:===============> ', params);
        let response = null;
        const { ctx } = this;
        try {
            let where = { uid: params?.uid ?? "" };
            const result = await ctx.model.Address.findAndCountAll({
                where,
                model: ctx.model.Address,
                attributes: [
                    "id",
                    "nickName",
                    "mobile",
                    "provincial",
                    "city",
                    "address",
                    "uid",
                    "is_default",
                ],

                order: [["id", "ASC"]], // 排序
                attributes: ["id", "nickName", "mobile", "provincial", "city", "address", "uid", "is_default"],

            });

            await Journal(ctx, { operatorType: "用户地址 -> 查询", code: 200 });
            response = successRes({
                records: result?.rows ?? [],

            });
        } catch (error) {
            console.error(error, "<---- error - 用户地址查询");
            await Journal(ctx, { operatorType: "用户地址 -> 查询", code: 401 });
            response = failRes(401);
        }
        return response;
    }


    //用户地址新增
    async wa_s_create_address(params) {
        let response = null;
        const { ctx } = this;
        let transaction;
        try {
            // 建立事务对象
            transaction = await ctx.model.transaction();
            await ctx.model.Address.create(
                params,
                { transaction },
                {
                    attributes: {
                        extends: ["id", "uid", "nickName", "mobile", "provincial", "city", "address", "is_default"],
                    },
                } // 向数据库插入特定字段
            );

            await transaction.commit();
            await Journal(ctx, { operatorType: "用户地址 -> 新增", code: 200 });
            response = successRes();
        } catch (error) {
            console.error(error, "<---- error - 用户地址新增");
            await transaction.rollback();
            await Journal(ctx, { operatorType: "用户地址 -> 新增", code: 401 });
            response = failRes(401);
        }
        return response;
    }

 //设置用户默认地址
 async wa_s_setdefault_address(params) {
    console.log(params, "<= params");
    let response = null;
    let transaction;
    const { ctx } = this;
    try {
        // 建立事务对象
        transaction = await ctx.model.transaction();

        // 查询用户默认地址并改为非默认

        const defaultAddresses = await ctx.model.Address.findAll({
            where: {
                uid: params.uid,
                is_default: 1,
            },
        },{ transaction },
            );
            // console.log(defaultAddresses, "<= defaultAddress");

            for (const defaultAddress of defaultAddresses) {
                await defaultAddress.update({ is_default: 0 }, { transaction });
            }

        // 设置默认地址

        await ctx.model.Address.update(
            { is_default: 1 },
            {
                where: { id: params.aid },
                
                attributes: { extends: ["id", "nickName", "mobile", "provincial", "city", "address", "uid"] },
                // attributes:  ["is_default"] ,
            },
            { transaction }
            // console.log(params, '<---- params - 账号管理编辑数据')
        );
        await transaction.commit();
        await Journal(ctx, { operatorType: "设置用户默认地址 -> 编辑", code: 200 });
        response = successRes();
    } catch (error) {
        transaction.rollback();
        console.error(error, "<---- error - 设置用户默认地址");
        await Journal(ctx, { operatorType: "设置用户默认地址 -> 编辑", code: 401 });
        response = failRes(401);
    }
    return response;
}


    //用户地址修改
    async wa_s_update_address(params) {
        console.log(params, "<= params");
        let response = null;
        let transaction;
        const { ctx } = this;
        try {
            // 建立事务对象
            transaction = await ctx.model.transaction();
            await ctx.model.Address.update(
                params,
                {
                    where: { id: params.id },
                    attributes: { extends: ["id"] },
                },
                { transaction }
                // console.log(params, '<---- params - 账号管理编辑数据')
            );
            await transaction.commit();
            await Journal(ctx, { operatorType: "用户地址修改 -> 编辑", code: 200 });
            response = successRes();
        } catch (error) {
            console.error(error, "<---- error - 用户地址修改");
            await Journal(ctx, { operatorType: "用户地址修改 -> 编辑", code: 401 });
            response = failRes(401);
        }
        return response;
    }

    //用户地址删除
    async wa_s_delete_address(params) {
        console.log(params, "<======= params");
        let response = null;
        const { ctx } = this;
        try {
            await ctx.model.Address.destroy({
                where: { 
                    id: params?.aid ?? "", 
                } 
            });
            await Journal(ctx, { operatorType: "用户地址删除 -> 删除", code: 200 });
            response = successRes();
        } catch (error) {
            console.error(error, "<---- error - 用户地址删除");
            await Journal(ctx, { operatorType: "用户地址删除 -> 删除", code: 401 });
            response = failRes(401);
        }
        return response;
    }

}
module.exports = sUser;
